<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // 记录sql语句的日志
        \Illuminate\Support\Facades\DB::listen(function ($query) {
            $tmp = str_replace('?', '"'.'%s'.'"', $query->sql);
            $qBindings = [];
            foreach ($query->bindings as $key => $value) {
                if (is_numeric($key)) {
                    $qBindings[] = $value;
                } else {
                    $tmp = str_replace(':'.$key, '"'.$value.'"', $tmp);
                }
            }
            $tmp = vsprintf($tmp, $qBindings);
            $tmp = str_replace("\\", "", $tmp);

            $logger = new Logger('mysql');
            $streamHander = new StreamHandler(storage_path('logs/mysql.log'), Logger::INFO);
            // 入栈, 往 handler stack 里压入 StreamHandler 的实例
            $logger->pushHandler($streamHander);
            $logger->info('execution time:' . $query->time.'ms; '. $tmp);
        });
    }

    public $singletons = [
        'security_lib' => \App\Libs\SecurityLib::class

    ];
}
